package com.gcb.socket.server;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;



public class MutliServer implements Runnable{
	
	private ServerSocket ss ;
	
	public MutliServer(){
		try {
			ss = new ServerSocket(4433);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
			
			MutliServer ms = new MutliServer();
			Thread t = new Thread(ms);
			t.start();
	}
	
	public class Listen extends Thread{

		Socket s = null;
		//BufferedReader in = null;
		//PrintWriter out = null;
		private DataInputStream dis;
		private DataOutputStream dos;
		String name = null;
		
		public Listen(Socket s) throws IOException{
			this.s = s;
			this.name = s.getInetAddress().getHostName();
			//this.in = new BufferedReader(new InputStreamReader(client.getInputStream()));
			//this.out = new PrintWriter(client.getOutputStream());
			dis = new DataInputStream(s.getInputStream());
			dos = new DataOutputStream(s.getOutputStream());
			this.start();
			BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
			while(true){
				String str = br.readLine();
				dos.writeUTF(sendMess(str));
				//dos.writeUTF(str);
				dos.flush();
				if("end".equals(str)){
					break;
				}
			}
		}
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				while(true){
					String str = dis.readUTF();
					getMess(str);
					if("end".equals(str)){
						break;
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		public void getMess(String str){
			System.out.println(str);
		}
		
		public String sendMess(String str){
			System.out.println("Server: " + str);
			return name + ": " + str;
		}
		
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		Socket s;
		try {
			s = ss.accept();
			new Listen(s);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
